package jianli;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class GiftServlet
 */
@WebServlet("/GiftServlet")
public class GiftServlet extends HttpServlet {//记录用户登录次数，满5次送品
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GiftServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setContentType("text/html;charset=UTF-8");
		Cookie myCookie = null;
        int age = 60 * 60 * 24 * 30;//30天
        boolean cookieFound = false;
        Cookie[] cookies = request.getCookies();//获取所有Cookie对象
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        HttpSession session=request.getSession();//取客户端请求中的session,如没有，则创建一个
        String id=session.getId();//取得sessionID
        String username=(String)session.getAttribute("username");  //获取session范围内保存的username
        out.print("本次会话ID："+id+"<br/>欢迎你！"+username);
        session.setAttribute("username", username);//将取到的请求参数设置入session属性
        out.print("<br/>你可以"+"<a href='ShowSession'>看看session信息详情</a>");
        //下面是记录用户访问次数。使用cookie技术，缺点是用户换浏览器后不能连续记数。通过使用上下文
        //这里要搞清ServletContext和ServletConfig的区别。前者作为整个Web应用的数据，后者只是在当前Servlet共享
        /*客户端换不同的浏览器servlet也会记住他来了多少次
         * ServletContext context = this.getServletContext();
	 		PrintWriter out = response.getWriter();
	 		Integer times =(Integer)context.getAttribute("times");
	 		if(times==null) {
		 		times = new Integer(1);
	 		}else {
		 		times = new Integer(times.intValue()+1);
	 		}
	 		out.println("<html><head><title>");
	 		out.println("页面访问统计~");
	 		out.println("</title></head><body>");
	 		out.println("当前页面被访问过了");
	 		out.println("<font color=red size=20>"+times+"</font>次");
	 		//设置属性，将times保存到当前的上下文中
	 		context.setAttribute("times", times);
         */
        if(cookies!= null) {
            for(int i = 0; i < cookies.length; i++) { //遍历Cookie数组，查找保存用户登录次数的Cookie
              if(cookies[i].getName().equals("loginCount")){  
                cookieFound = true;
                myCookie = cookies[i];
            }
          }
        }
        if(cookieFound) {//如果找到Cookie，更新用户访问次数
          int temp = Integer.parseInt(myCookie.getValue());
          temp++;
          if(temp == 5){
            out.println("<br/>恭喜你!!!!!!!!!!!第5次访问有神秘礼物相送！<br/>");
          }
          out.println("<br/>你是第" + String.valueOf(temp) + "次访问本站点");
          myCookie.setValue(String.valueOf(temp));
          cookieFound = false;// 如果cookieFound设置为类的成员变量，此语句一定要写
        }else{//用户第一次访问，创建值为1的Cookie对象loginCount
          int temp = 1;
          out.println("<br/>你是第1次访问本站点");
          myCookie = new Cookie("loginCount", String.valueOf(temp));
        }
        myCookie.setMaxAge(age);//设置Cookie有效期
        response.addCookie(myCookie);//将最新的Cookie对象写给客户端
        out.println("</body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
